package dao

import (
	"context"
	"mini-app/internal/dal"
	"mini-app/internal/models"

	"192.168.1.75/go-pkg/errorx"
)

type GoodsClass struct{}

// ExistsByID
func (GoodsClass) ExistsByID(
	ctx context.Context,
	query *dal.Query,
	id string,
) bool {
	c := query.GoodsClass
	count, _ := c.WithContext(ctx).Where(c.ID.Eq(id)).Count()
	return count > 0
}

// ExistsByName
// id  可选
// name 可选
func (GoodsClass) ExistsByName(
	ctx context.Context,
	query *dal.Query,
	name string,
) bool {
	c := query.GoodsClass
	count, _ := c.WithContext(ctx).Where(c.Name.Eq(name)).Count()
	return count > 0
}

// Add 新增分类
func (GoodsClass) Add(
	ctx context.Context,
	query *dal.Query,
	name string,
) error {
	c := query.GoodsClass
	err := c.WithContext(ctx).Create(&models.GoodsClass{
		Name: name,
	})
	return err
}

// Update 更新分类
func (GoodsClass) Update(
	ctx context.Context,
	query *dal.Query,
	id string,
	name string,
) error {
	c := query.GoodsClass
	res, _ := c.WithContext(ctx).Where(c.ID.Eq(id)).Updates(&models.GoodsClass{
		Name: name,
	})
	if res.RowsAffected <= 0 {
		return errorx.New("更新失败", -1)
	}
	return nil
}

// Delete 删除分类
func (GoodsClass) Delete(
	ctx context.Context,
	query *dal.Query,
	classID string,
) error {
	c := query.GoodsClass
	// 在使用的分类不能被删除
	if (GoodsSetting{}).Exists(ctx, dal.Q, "", "", classID) {
		return errorx.New("使用中的分类不能删除", -1)
	}
	// 删除
	_, err := c.WithContext(ctx).Where(c.ID.Eq(classID)).Delete(&models.GoodsClass{})
	return err
}

// List 分类列表
func (GoodsClass) List(
	ctx context.Context,
	query *dal.Query,
) ([]*models.GoodsClass, error) {
	c := query.GoodsClass
	return c.WithContext(ctx).Order(c.ID).Find()
}

func (GoodsClass) Detail(
	ctx context.Context,
	query *dal.Query,
	ID string,
) (*models.GoodsClass, error) {
	c := query.GoodsClass
	return c.WithContext(ctx).Where(c.ID.Eq(ID)).Take()
}
